<?php

namespace App\Console\Dispatch;


use App\Models\News;
use App\Models\SiteTagSpider;

class Cts extends Base
{
    /**
     * 请求：
     *  sudo -u www php artisan command:dispatch-cts
     *  sudo -u www php /www/wwwroot/apiasiatechwire/artisan command:dispatch-cts
     *
     */
    /**
     * 参数与选项的区别
     *      在执行命令时，参数必须严格按定义时的顺序输入，不需输入参数名，只需输入参数的值即可。
     *      输入选项则必须带选项名，且选项名前须加 -- 前缀（选项简写字母前加 -），选项可按任意顺序输入
     */

    // 请求 以及参数
    // protected $signature = 'command:name {param1} {param2}';  // 必填参数
    // protected $signature = 'command:name {参数名?} {参数名=默认值} {参数名? : 参数说明}';  // 可选参数
    // protected $signature = 'command:name {--选项名} {--选项名=} {--选项名=默认值} {--简写字母|选项名} {--选项名 : 选项说明}';  // 选项
    protected $signature = 'command:dispatch-cts';

    protected $description = '定时任务：从财通社采集快讯数据';  // TODO 定时任务

    // 记录数据量
    protected $numbers;
    protected $strNumber;
    protected $picKeys;

    // 执行的命令
    public function handle()
    {
        $num   = 100;
        $start = 2550000;
        $start = 2557000;
        $start = 2557769;

        // 图片
        $path     = public_path('picture');
        $pathKeys = $this->readDir($path, true, false);
        // 开始执行
        $start    = $this->getNewsMaxId($start);
        $keywords = $this->getKeywords();  // 获取关键词，用于采集快讯的关键词
        // 组合
        $this->picKeys = ['path' => $path, 'url_path' => 'picture/', 'keywords' => $pathKeys];

        // 执行
        while($start){
            $start = $this->toMigration($keywords, $start, $num);

            $this->comment('继续下一次采集：开始ID：'.$start);
        }


        /*$cline = chr(10);
        echo $cline.$cline;
        var_export($this->numbers);
        echo $cline.$cline;
        var_export($this->strNumber);
        echo $cline.$cline;

        $days = count($this->numbers);
        $tiao = array_sum($this->numbers);
        $all  = array_sum($this->strNumber);
        echo '天数：'.$days.$cline;
        echo '条数：'.$tiao.$cline;
        echo '条数/天：'.($tiao / $days).$cline;
        echo '字符数：'.$all.$cline;
        echo '字符/天：'.($all / $days).$cline;
        echo $cline.$cline;*/

        return $this->showMsg('采集完成！');
    }

    // 执行迁移
    protected function toMigration($keywords, $start, $num)
    {
        // 获取财通社快讯
        $result = $this->ctsData($start, $num);
        $lists  = $result['list'];
        if(empty($lists)){
            $this->line('没有数据需要迁移！');

            return false;
        }

        $this->line('  共获取到'.count($lists).'条');

        // 保存快讯
        $start = $this->saveList($keywords, $lists, $start);

        // 释放内存
        $this->sqlLog();

        return $start;
    }

    // 保存
    protected function saveList($keywords, $lists, $start)
    {
        $filter    = ['主力合约', '期货', '主力资金', '注册资本', '法定代表人', '经营范围', '成交量'];
        $numbers   = $this->numbers;
        $strNums   = $this->strNumber;
        $picPath   = $this->picKeys['path'];
        $picKeys   = $this->picKeys['keywords'];
        $url_path  = $this->picKeys['url_path'];
        $oldDomain = env('OLD_HOST');


        foreach($lists as $key => $item){
            // 内容处理
            $brief = $item['brief'];
            $start = max($start, $item['id']);
            $brief = $this->removeOrigin($brief);  // 2、取消来源 最后一位是 ） )
            if(empty($brief)){
                continue;
            }
            // 内容对比关键词
            $en_keyword = [];
            $cn_keyword = [];
            foreach($keywords as $_keyRow){
                if(mb_strpos($brief, $_keyRow['cn_title']) !== false){
                    if(in_array($_keyRow['cn_title'], $cn_keyword)){
                        continue;
                    }
                    $en_keyword[] = $_keyRow['en_title'];
                    $cn_keyword[] = $_keyRow['cn_title'];
                }
            }
            // 如果没有匹配到关键词 则不要
            if(empty($en_keyword) && empty($cn_keyword)){
                continue;
            }
            // 匹配图片
            $pic = $picName = '';
            foreach($picKeys as $_key){
                $_keys = explode('、', $_key);
                foreach($_keys as $_k){
                    if(empty($_k)){
                        continue;
                    }
                    if(mb_strpos($brief, $_k) !== false){
                        if(empty($picName)){
                            $picName = $_key;
                        } else{
                            $picName = mb_strlen($_key) > mb_strlen($picName) ? $_key : $picName;
                        }
                    }
                }
            }
            if($picName){
                // 获取json文件
                $f_json = $picPath.DIRECTORY_SEPARATOR.'pic.json';
                $_json  = json_decode(file_get_contents($f_json), true);
                // 获取图片
                $_path = $picPath.DIRECTORY_SEPARATOR.$picName;
                $_url  = $oldDomain.$url_path.$picName;
                //$_url  = $oldDomain.$url_path.urlencode($picName);
                $_pics = $this->readDir($_path, true, false);
                if($_pics){
                    //$pic = $_url.'/'.$_pics[array_rand($_pics, 1)];
                    if(isset($_json[$picName])){
                        $_number = $_json[$picName] == count($_pics) - 1 ? 0 : $_json[$picName] + 1;
                    } else{
                        $_number = 0;
                    }
                    $pic = $_url.'/'.$_pics[$_number];
                }
                // 保存json文件
                $_json[$picName] = $_number;
                file_put_contents($f_json, json_encode($_json, JSON_UNESCAPED_UNICODE));
            }

            // 内容处理
            // 1、添加中国 国家知识产权局      国家信息中心
            $brief = str_replace('国家知识产权局', '中国国家知识产权局', $brief);
            $brief = str_replace('国家信息中心', '中国国家信息中心', $brief);

            // 3、区分内容和标题
            if(mb_substr($brief, 0, 1) == "【"){
                $pos     = mb_strpos($brief, "】");
                $content = mb_substr($brief, $pos + 1);
                $title   = mb_substr($brief, 1, $pos - 1);
                $title   = mb_substr($title, 0, 150);
            } else{
                $content = $brief;
                $title   = '';
            }

            // 如果超过 500 个字 则不要
            /*if(mb_strlen($content) > 500){
                continue;
            }*/


            // 记录数据量
            $_date           = date('Y-m-d', $item['create_time']);
            $numbers[$_date] = ($numbers[$_date] ?? 0) + 1;
            $strNums[$_date] = ($strNums[$_date] ?? 0) + mb_strlen($brief) + 20;  // +20：避免老板多用钱，秋后算账

            // 组合数据
            $images = $item['images'] ?: json_encode([]);
            $row    = [
                'pic'         => $pic,
                'title'       => $title,
                'desc'        => $content,
                'images'      => $images,
                'is_major'    => $item['is_major'] == 'enabled' ? 1 : 0,
                'verify'      => 1,
                'uid'         => 1,
                'cn_keywords' => $cn_keyword,
                'en_keywords' => $en_keyword,
                'time'        => $item['create_time'],
                'url'         => $item['id'], // views,virtual_views
                'read_no'     => $item['views'],
                'virtual_no'  => $item['virtual_views'],
                'site'        => 'caitongnews',
            ];

            // 组合数据
            $insert[] = $row;
            // 保存到数据库
            $this->saveRow($row, $filter);
        }

        // 保存数据量
        $this->numbers   = $numbers;
        $this->strNumber = $strNums;

        return $start;
    }

    // 获取所有的关键词
    protected function getKeywords()
    {
        //$lists = DB::table('site_tag_spider')->get()->toArray();
        $lists = (new SiteTagSpider())->get()->toArray();

        return $lists;
    }

    // 获取财通社数据
    protected function ctsData($start, $num)
    {
        $this->line('获取迁移数据第'.$start.'条开始，获取'.$num.'条');

        //$url  = "http://api.ctsnews.com/v2/slh/dispatch";  // 本地电脑
        $url  = "http://newapi.caitongnews.com/v2/slh/dispatch";
        $data = ['page' => 1, 'size' => $num, 'maxId' => $start];
        $http = new \GuzzleHttp\Client();
        $post = ['body' => json_encode($data), 'headers' => ['Content-Type:multipart/form-data']];
        try{
            $res    = $http->post($url, $post);
            $body   = $res->getBody();  // 字符串
            $header = $res->getHeaders(); // 数组
            $bodys  = json_decode($body, 1);
            if($bodys['code'] == 200){
                $data = $bodys['data'];

                //var_dump($data['d3']);
                return $data;
            } else{
                die($bodys['msg']);
            }

        } catch(\Exception $e){
            return [];
        }
    }

    // 获取财通社的最大id
    protected function getNewsMaxId($start)
    {
        // 获取财通社来源的新闻的id
        $info = (new News())->where('from_site', 'caitongnews')->selectRaw("max(from_url) as num")->first();
        if(empty($info)){
            return $start;
        }

        return max($info->num, $start);
    }

}
